import json
import os
import threading
import time

from  apilib.component import compManager , TComp

class TCompBucket( TComp):
    def __init__(self):
        super().__init__()
        #key,updated, objs
        self.buckets={}
        self.handlers={
            "getObjs": self.getBucketObjs,
            "setObjs": self.setBucketObjs,
        }
        self.autoStartServices={}
        self.saveTime = time.time()
        self.updateFlag = False
    def compInit(self):
        try:
            self.loadBuckets()
            (threading.Thread(target=self.loopSave , daemon=True)).start()
        except Exception as er:
            self.manager.log(er)
    def loadBuckets(self):
        try:
            bucketPath = self.compSettings['bucketPath']
            bucketMetaFn = os.path.join(bucketPath , "bucketKeys.json")
            if os.path.exists(bucketMetaFn):
                bks = []
                with open(bucketMetaFn,'r',encoding='utf-8') as f:
                    try:
                        content = f.read()
                        bks = json.loads(content)
                    except Exception as er:
                        self.manager.log(er)
                for bk in bks:
                    try:
                        self.buckets[bk]={
                            "key": bk ,
                            "updated": 0 ,
                            "objs":{}
                        }
                        dataFn = os.path.join(bucketPath , f"bk_{bk}.json")
                        if( os.path.exists(dataFn) ):
                            with open(dataFn,'r',encoding='utf-8') as f:
                                try:
                                    content = f.read()
                                    self.buckets[bk]['objs'] = json.loads(content)
                                except Exception as er:
                                    self.manager.log(er)

                    except Exception as er:
                        self.manager.log(er)

        except Exception as er:
            self.manager.log(er)
    def saveBuckets(self):
        try:
            if self.updateFlag :
                bucketPath = self.compSettings['bucketPath']
                if not os.path.exists(bucketPath):
                    os.makedirs(bucketPath, 0x777)
                keys = list(self.buckets.keys())
                bucketMetaFn = os.path.join(bucketPath , "bucketKeys.json")
                with open( bucketMetaFn,'w',encoding='utf-8' ) as f:
                    f.write(json.dumps(keys , ensure_ascii=False))
                for  bucket in self.buckets.values():
                    if bucket['updated']>0:
                        bucketFn = os.path(bucketPath , f"bk_{bucket['key']}.json")
                        with open(bucketFn ,'w', encoding='utf-8') as f:
                            try:
                                content = json.dumps(bucket['objs'] , ensure_ascii=False)
                                f.write(content)
                            except Exception as eer:
                                self.manager.log(eer)
                        bucket['updated'] = 0
                self.updateFlag = False
        except Exception as er:
            self.manager.log(er)
    def loopSave(self):
        try:
            while 1>0:
                time.sleep(1)
                nowTm = time.time()
                if nowTm-15 > self.saveTime:
                    self.saveTime = nowTm
                    self.saveBuckets()
        except Exception as er:
            self.manager.log(er)
    def getBucketObjs(self , bucketCode , objKeys=[]):
        res ={
            "status":0,
            "objs":{}
        }
        try:
            if  bucketCode in self.buckets.keys():
                objs = self.buckets[bucketCode]['objs']
                for k in objKeys:
                    if k in objs.keys():
                        res['objs'][k] = objs[k]
                    else:
                        res['objs'][k] = None
            else:
                res['status']= -2000

        except Exception as er:
            self.manager.log(er)
    def setBucketObjs(self , bucketCode , dictObjs={}):
        res ={
            "status":0
        }
        try:
            if not  bucketCode in self.buckets.keys():
                self.buckets[bucketCode]={
                    "key": bucketCode ,
                    "updated": 1 ,
                    "objs":{}
                }
            bucket = self.buckets[bucketCode]
            bucket['updated'] = 1
            for k,o in dictObjs.items():
                bucket['objs'][k] = o
            if not self.updateFlag:
                self.updateFlag = True

            res['status'] = 1

        except Exception as er:
            self.manager.log(er)
        return  res
_settings = {
    "bucketPath":"/data/devhhinfo/buckets"
}
compManager.registComponentType('TCompBucket' , TCompBucket , _settings)

